<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>虚拟设备</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="search-form">
      <el-form-item>
        <el-button size="small" icon="el-icon-plus" @click="createDevice"
          >创建</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="$store.state.loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="index" width="60">
      </el-table-column>
      <el-table-column
        sortable
        prop="name"
        label="名称"
        width="250"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="productKey"
        label="产品"
        width="150"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ productMap[scope.row.productKey] }}
        </template>
      </el-table-column>
      <el-table-column
        sortable
        prop="type"
        label="类型"
        width="120"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ typeName[scope.row.type] }}
        </template>
      </el-table-column>
      <el-table-column
        sortable
        prop="trigger"
        label="触发方式"
        width="100"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ triggerName[scope.row.trigger] }}
        </template>
      </el-table-column>
      <el-table-column
        sortable
        prop="state"
        label="状态"
        width="80"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state == 'running'"
            type="success"
            size="mini"
            plain
            @click="setState(scope.row.id, 'stopped')"
            >运行中</el-button
          >
          <el-button
            v-if="scope.row.state == 'stopped'"
            type="danger"
            size="mini"
            plain
            @click="setState(scope.row.id, 'running')"
            >已停止</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        sortable
        prop="createAt"
        label="创建时间"
        width="180"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <div>{{ scope.row.createAt | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="infor"
            @click="goDeviceDetail(scope.$index, scope.row)"
            >配置</el-button
          >
          <el-button
            size="mini"
            type="infor"
            @click="showModify(scope.$index, scope.row)"
            >修改</el-button
          >
          <el-popconfirm
            title="确认要删除吗？"
            @confirm="deleteDevice(scope.$index, scope.row)"
            class="mg-left-10"
          >
            <el-button slot="reference" size="mini" plain type="danger"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="editForm.id ? '创建虚拟设备' : '修改虚拟设备'"
      :visible.sync="showCreateDevice"
      width="500px"
    >
      <el-form ref="form" :model="editForm" :rules="rules" label-width="100px">
        <el-form-item label="产品" prop="productKey">
          <el-select
            size="small"
            v-model="editForm.productKey"
            placeholder="请选择产品"
          >
            <el-option
              v-for="pro in products"
              :label="pro.name"
              :value="pro.id"
              :key="pro.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            size="small"
            v-model="editForm.name"
            placeholder=""
          ></el-input>
        </el-form-item>
        <el-form-item label="虚拟类型" prop="type">
          <el-radio-group v-model="editForm.type" size="mini">
            <el-radio-button label="thingModel">基于物模型</el-radio-button>
            <el-radio-button label="protocol">基于设备协议</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="触发方式" prop="trigger">
          <el-radio-group v-model="editForm.trigger" size="mini">
            <el-radio-button label="none">无（手动）</el-radio-button>
            <el-radio-button label="cron">定时执行</el-radio-button>
            <el-radio-button label="random">随机执行</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="editForm.trigger == 'cron'"
          label="cron表达式"
          prop="triggerExpression1"
        >
          <el-input
            size="small"
            v-model="editForm.triggerExpression1"
            placeholder=""
          >
            <template slot="append">
              <a href="http://cron.ciding.cc/" target="_blank"
                >cron表达式生成器</a
              >
            </template></el-input
          >
        </el-form-item>
        <el-form-item
          v-if="editForm.trigger == 'random'"
          label="随机单位"
          prop="triggerExpression2"
        >
          <el-radio-group v-model="editForm.triggerExpression2" size="mini">
            <el-radio-button label="second">秒</el-radio-button>
            <el-radio-button label="minute">分</el-radio-button>
            <el-radio-button label="hour">时</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitDeviceCreate" size="small"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页组件 -->
    <Pagination :data="formInline" @onPagePaging="search"></Pagination>
  </div>
</template>

<script>
import {
  VirtualDeviceList,
  VirtualDeviceAdd,
  VirtualDeviceModify,
  VirtualDeviceDelete,
  VirtualDeviceSetState,
} from "../../api/deviceApi";
import { ProductList } from "../../api/productApi";
import Pagination from "../../components/Pagination";
export default {
  data() {
    var checkExpression = (rule, value, callback) => {
      if (this.editForm.trigger == "cron" && !value) {
        return callback(new Error("表达式不能为空"));
      } else if (this.editForm.trigger == "random" && !value) {
        return callback(new Error("随机单位不能为空"));
      }
      callback();
    };

    return {
      showCreateDevice: false,
      chidrenDevicesVisiable: false,
      title: "",
      formInline: {
        page: 1,
        size: 10,
        total: 0,
      },
      editForm: {
        id: "",
        productKey: "",
        deviceName: "",
        type: "thingModel",
        trigger: "none",
        triggerExpression: "",
        triggerExpression1: "1-1 * * * * ?",
        triggerExpression2: "minute",
      },
      rules: {
        productKey: [
          { required: true, message: "请选择产品", trigger: "blur" },
        ],
        name: [{ required: true, message: "请填写名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择虚拟类型", trigger: "blur" }],
        trigger: [
          { required: true, message: "请选择触发方式", trigger: "blur" },
        ],
        triggerExpression1: [{ validator: checkExpression, trigger: "blur" }],
        triggerExpression2: [{ validator: checkExpression, trigger: "blur" }],
      },
      products: [],
      listData: [],
      productMap: {},
      typeName: {
        thingModel: "基于物模型",
        protocol: "基于设备协议",
      },
      triggerName: {
        none: "无（手动）",
        cron: "定时执行",
        random: "随机执行",
      },
    };
  },
  components: {
    Pagination,
  },
  created() {
    this.search();
  },
  methods: {
    search() {
      this.getdata(this.formInline);
    },
    getdata(parameter) {
      ProductList({ page: 1, size: 1000 }).then((res) => {
        this.products = res.data;
        let nodeTypeMap = {};
        res.data.forEach((p) => {
          this.productMap[p.id] = p.name;
          nodeTypeMap[p.id] = p.nodeType;
        });

        VirtualDeviceList(parameter).then((res) => {
          this.listData = res.data;
          res.data.forEach((d) => {
            if (d.trigger == "cron") {
              d.triggerExpression1 = d.triggerExpression;
            } else if (d.trigger == "random") {
              d.triggerExpression2 = d.triggerExpression;
            }
          });
          this.formInline.total = res.total;
        });
      });
    },
    createDevice() {
      this.showCreateDevice = true;
    },
    submitDeviceCreate() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.editForm.trigger == "random") {
            this.editForm.triggerExpression = this.editForm.triggerExpression2;
          } else if (this.editForm.trigger == "cron") {
            this.editForm.triggerExpression = this.editForm.triggerExpression1;
          }

          if (this.editForm.id) {
            VirtualDeviceModify(this.editForm).then(() => {
              this.$notify({
                title: "成功",
                message: "修改成功",
                type: "success",
              });
              this.showCreateDevice = false;
            });
          } else {
            VirtualDeviceAdd(this.editForm).then(() => {
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
              });
              this.showCreateDevice = false;
              this.search();
            });
          }
        }
      });
    },
    showModify(index, row) {
      this.editForm = row;
      this.showCreateDevice = true;
    },
    goDeviceDetail(index, row) {
      this.$router.push({
        path: "/device/VirtualDeviceDetail",
        query: {
          id: row.id,
        },
      });
    },
    deleteDevice(index, row) {
      VirtualDeviceDelete(row.id).then(() => {
        this.search();
      });
    },
    setState(id, state) {
      VirtualDeviceSetState({ id: id, state: state }).then(() => {
        this.search();
      });
    },
  },
};
</script>